package com.isyscore.os.metadata.common.dict;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;

import java.util.Objects;
import java.util.concurrent.TimeUnit;


public abstract class CachedDictTranslater implements DictTranslater {

    private Cache<Integer, String> dictCache = CacheBuilder.newBuilder()
            .maximumSize(1000)
            .expireAfterWrite(60, TimeUnit.MINUTES)
            .build();

    @Override
    public String getLabelByCode(String dictType, Object dictCode) {
        String dictLabel = dictCache.getIfPresent(getCacheKey(dictType, dictCode));
        if (dictLabel == null) {
            dictLabel = doGetLabelByCode(dictType, dictCode);
            if (dictLabel == null) {
                dictLabel = "";
            }
            dictCache.put(getCacheKey(dictType, dictCode), dictLabel);
        }
        return dictLabel;
    }

    public abstract String doGetLabelByCode(String dictType, Object dictCode);


    private int getCacheKey(String dictType, Object dictCode) {
        return Objects.hash(dictType, dictCode);
    }


}
